var http = require('http');
var ip = '127.0.0.1'
var port = 80
var fs = require('fs');
var url = require('url');
var querystring = require('querystring');
var setName = "HY的留言板";

var mysql = require('mysql');
var client = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: '123456',
    database:'massegeboard',
    port: 3306
});
client.connect();

http.createServer(function (request, response) {
	response.setCode=200;
	response.setHeader('Content-Type', 'text/html');
	var ext = request.url.substr(request.url.lastIndexOf('.')+1)
	var exts={
		'html':'text/html',
		'css':'text/css',
		'js':'text/javascript',
		'png':'image/png',
		'jpg':'image/jpeg',
	}
	if(exts[ext] == null){
		exts[ext] = 'text/plain';
	}
	response.setHeader('Content-Type', exts[ext]);
	/*if(d == 'css'){
		response.setHeader('Content-Type', 'text/css');
	}else if(d == '.js'){
		response.setHeader('Content-Type', 'application/x-javascript');
	}*/
	var data = '404'

	var p = url.parse(request.url,true)
	if(p.pathname == '/index.html'){
		try{
			data = fs.readFileSync('.'+ request.url,'utf-8');
			
			client.query('select * from massegeboards', function(err, rows, fields) {
			    if (err) throw err;
			    var m=rows
			    var s='';
				for (var i = 0; i < m.length; i++) {
					s+='<div class="item">';
					s+='<h6>'+m[i].author+'<span>'+m[i].time+'</span></h6>';
					s+='<p>'+m[i].message+'<a href="/delmessage?id='+m[i].Id+'">删除</a></p>';
					s+='</div>';
				}
				data = data.replace(/%main/g,s)
				data = data.replace(/%title/g,setName)

				response.write(data)
				response.end();
			});
			
			
		}catch(e){
		}
	}else if(p.pathname == '/form.html'){
		data = fs.readFileSync('.'+ request.url,'utf-8');
		response.write(data)
		response.end();
	}else if(p.pathname == '/addmessage'){
		/*author = p.query.author;
		message = p.query.message;
		m = JSON.parse(fs.readFileSync('data.json','utf8'));
		m.push({
			author:author,
			message:message,
			time:new Date()
		})
		m = JSON.stringify(m)
		fs.writeFileSync('data.json',m)
		response.writeHead(302,{
			'location':'/index.html'
		})*/
		var post = '';     
 		// 通过req的data事件监听函数，每当接受到请求体的数据，就累加到post变量中
	    request.on('data', function(chunk){    
	        post += chunk;
	    });
	 
	    // 在end事件触发后，通过querystring.parse将post解析为真正的POST请求格式，然后向客户端返回。
	    request.on('end', function(){
	    	m = querystring.parse(post);

			client.query('insert into massegeboards values(null,"'+m.author+'","'+m.message+'","'+new Date()+'")', function(err, rows, fields) {
			    if (err) throw err;
			});
			client.end();

			response.writeHead(302,{
				'location':'/index.html'
			})
			response.write(data)
			response.end();
    	});
	}else if (p.pathname =='/delmessage'){		
		id = p.query.id;
		client.query("delete from massegeboards where id="+id, function(err, rows, fields) {
		    if (err) throw err;
		    response.writeHead(302,{
				'location':'/index.html'
			})
			response.write(data)
			response.end();
		});
		client.end();
		
	}
	
}).listen(port);

// 终端打印如下信息
console.log('Server running at http://%s:%s/',ip,port);